﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using NetTaste;
using Org.BouncyCastle.Bcpg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    /// <summary>
    /// 托盘管理
    /// </summary>
    public class PalletRepository: BaseRepository<TPallet>, IPalletRepository
    {
        public PalletRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool AddPallet(PalletDto dto)
        {
            try
            {
                TPallet pallet = new TPallet();
                pallet = Mapper.Map<TPallet>(dto);
                pallet.CreateDate = DateTime.Now;
                Context.TPallets.Add(pallet);
                return Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool UpdatePallet(PalletDto dto)
        {
            try
            {
                var pallobj = Context.TPallets.AsNoTracking().FirstOrDefault(x => x.PalletBarcode == dto.PalletBarcode && x.Id != dto.Id);
                if (pallobj!=null)
                {
                    return false;
                }
                TPallet pallet = new TPallet()
                {
                    Id=dto.Id,
                    PalletBarcode = dto.PalletBarcode,
                    PalletName = dto.PalletName,
                    LocationCode = dto.LocationCode,
                    Status = dto.Status,
                    CreateDate = dto.CreateDate,
                    ModifyDate=DateTime.Now,
                    DisplayOrder = dto.DisplayOrder,
                    Opprint = dto.Opprint,
                    PrintTimes = dto.PrintTimes,
                    LocationName = dto.LocationName,
                    ErplocationName = dto.ErplocationName,
                    Type = dto.Type,
                    WarehouseId = dto.WarehouseId,
                    WarehouseCode = dto.WarehouseCode,
                    WarehouseName = dto.WarehouseName
                };
                Context.TPallets.Update(pallet);
                return Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DelPallet(int ids)
        {
            try
            {
                var pall = Context.TPallets.Find(ids);
                Context.TPallets.Remove(pall);
                return Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 托盘分页查询
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<TPallet> GetPallets(string name,int type, int incell, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var list = Context.TPallets.AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    list = list.Where(x => x.PalletName.Contains(name));
                }
                if (incell > 0)
                {
                    if (incell == 1)
                    {
                        list = list.Where(x => x.LocationCode == null);
                    }
                    if (incell == 2)
                    {
                        list = list.Where(x => x.LocationCode != null);
                    }
                }
                
                if (type != -1)
                {
                    list = list.Where(x => x.Type == type);
                }
                totalCount = list.Count();
                list = list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                
                return list.ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TPallet GetPallet(int id)
        {
            return Context.TPallets.Find(id);
        }
        
        /// <summary>
        /// 根据托盘类型查询托盘
        /// </summary>
        /// <param name="palletType"></param>
        /// <returns></returns>
        public List<TPallet> GetTypePallet(int palletType)
        {
            return Context.TPallets.Where(p=>p.Type==palletType).ToList();
        }

        public bool BatchAddPallet(List<TPallet> pallets)
        {
            if (pallets.Count>0)
            {
                using (var trans = Context.Database.BeginTransaction())
                {
                    try
                    {
                        foreach (var item in pallets)
                        {
                            Context.TPallets.Add(item);
                            Context.SaveChanges();
                        }
                        Context.SaveChanges();
                        //提交事务
                        trans.Commit();
                        return true;
                    }
                    catch (Exception)
                    {

                        //事务回滚
                        trans.Rollback();
                        throw;
                    }
                } 
            }
            return false;
        }

        /// <summary>
        /// 批量添加托盘
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPalletList(BatchPalletDTO m, out string message)
        {
            message = string.Empty;
            string name = "";
            if (m.Type == 0)
            {
                name = "托盘-";
            }
            else if (m.Type == 1)
            {
                name = "料箱800*600-";
            }
            else if (m.Type == 2)
            {
                name = "料箱600*400-";
            }
           
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    string pattern = @"\d+$";
                    Match match = Regex.Match(m.BeginBarcode, pattern);
                    string value = match.Value;
                    int values = Convert.ToInt32(value);
                    int valuelenth = value.Length;

                    int allvaluelenth = m.BeginBarcode.Length;

                    string name1 = m.BeginBarcode.Substring(0, allvaluelenth - valuelenth);

                    
                    for (int i = 0; i < m.Num; i++)
                    {
                        TPallet p = new TPallet();
                        //p.PalletName = string.Concat(name, m.BeginBarcode.AsSpan(m.BeginBarcode.Length - 7));
                        string formattedValue = values.ToString("D6"); // 转换为六位数字符串  
                        p.PalletName = string.Concat(name, formattedValue);
                        p.PalletBarcode = name1 + formattedValue; ;
                        p.Type = m.Type;
                        p.Opprint = m.IsPrint;
                        p.CreateDate = DateTime.Now;
                        p.Status = 1;
                        p.ModifyDate = DateTime.Now;
                        var res = Context.TPallets.FirstOrDefault(t => t.PalletBarcode == p.PalletBarcode || t.PalletName == p.PalletName);
                        if (res is not null)
                        {
                            message = "添加失败,托盘条码" + p.PalletBarcode + "或托盘名称" + p.PalletName + "已存在";
                            trans.Rollback();
                            return false;
                        }
                        Context.TPallets.Add(p);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "批量添加托盘失败";
                            trans.Rollback();
                            return false;
                        }
                        //startvalue = m.BeginBarcode.Substring(0, m.BeginBarcode.Length - 7);
                        //value = Convert.ToInt32(m.BeginBarcode.Substring(m.BeginBarcode.Length - 7));
                        //value++;
                        //endvalues = value.ToString("D7");
                        //m.BeginBarcode = startvalue + endvalues;
                        values++;
                    }
                    trans.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    trans.Rollback();
                    return false;
                    throw;
                }
            }

        }
    }
}
